import React, { useEffect, useState } from 'react';
import { BbsApi, Post, UserInfo } from '../src';

// 初始化 API 实例
const api = new BbsApi({
  baseURL: 'http://localhost:3000',
});

// 帖子列表组件
const PostList: React.FC = () => {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      try {
        const response = await api.post.getPosts({
          page: 1,
          pageSize: 10,
        });
        setPosts(response.data.list);
      } catch (error) {
        console.error('获取帖子列表失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchPosts();
  }, []);

  return (
    <div className="post-list">
      <h1>帖子列表</h1>
      {loading ? (
        <div>加载中...</div>
      ) : (
        <div>
          {posts.map((post) => (
            <PostItem key={post.id} post={post} />
          ))}
        </div>
      )}
    </div>
  );
};

// 帖子详情组件
const PostItem: React.FC<{ post: Post }> = ({ post }) => {
  const [liked, setLiked] = useState(false);

  const handleLike = async () => {
    try {
      if (liked) {
        await api.post.unlikePost(post.id);
        setLiked(false);
      } else {
        await api.post.likePost(post.id);
        setLiked(true);
      }
    } catch (error) {
      console.error('操作失败:', error);
    }
  };

  return (
    <div className="post-item">
      <h2>{post.title}</h2>
      <p>{post.content}</p>
      <div className="post-meta">
        <span>作者: {post.author.username}</span>
        <span>浏览: {post.viewCount}</span>
        <span>
          <button onClick={handleLike}>
            {liked ? '取消点赞' : '点赞'} ({post.likeCount})
          </button>
        </span>
      </div>
      <CommentList postId={post.id} />
    </div>
  );
};

// 评论列表组件
const CommentList: React.FC<{ postId: number }> = ({ postId }) => {
  const [comments, setComments] = useState<Comment[]>([]);
  const [content, setContent] = useState('');

  useEffect(() => {
    const fetchComments = async () => {
      try {
        const response = await api.comment.getComments(postId, {
          page: 1,
          pageSize: 10,
        });
        setComments(response.data.list);
      } catch (error) {
        console.error('获取评论失败:', error);
      }
    };

    fetchComments();
  }, [postId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!content.trim()) return;

    try {
      const response = await api.comment.createComment(postId, content);
      setComments([...comments, response.data]);
      setContent('');
    } catch (error) {
      console.error('发表评论失败:', error);
    }
  };

  return (
    <div className="comment-section">
      <h3>评论</h3>
      <form onSubmit={handleSubmit}>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder="写下你的评论..."
        />
        <button type="submit">发表评论</button>
      </form>
      <div className="comment-list">
        {comments.map((comment) => (
          <div key={comment.id} className="comment-item">
            <p>{comment.content}</p>
            <div className="comment-meta">
              <span>作者: {comment.author.username}</span>
              <span>时间: {new Date(comment.createTime).toLocaleString()}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}; 